#!usr/local/bin/python
import Bio.SeqIO
import sys
import os
import subprocess
import re
from Bio import SeqIO
HMM_DIRECTORY = "/progs/split/hmmtop_2.1/"
class submitSequence:
    def readFile(self,filename,value):
        f=open(filename,"rw")
        rHMMT=runHMMTOP()
        for record in SeqIO.parse(f,"fasta"):
            fasta_file=open("query.faa","w")
            fasta_file.write(">"+record.name+"\n"+str(record.seq))
            fasta_file.close()
            rHMMT.executeHMMTOP(record,value)
    def main(self):
        filename=sys.argv[1]
        value=sys.argv[2]
        self.readFile(filename,value)  
class runHMMTOP:
    
    def executeHMMTOP(self,record,value):
        cmd=subprocess.Popen(HMM_DIRECTORY+"hmmtop -if='/Users/Ankur/query.faa' -pl",shell=True,stdout=subprocess.PIPE) 
      
        output=cmd.communicate()[0]
        pattern='pred\s+([ ,A-Za-z]+)\s+\n'
        results = re.findall(pattern,output)
        string = ''.join(results).replace(" ","")
        toggle=0
        position_list=[]
        for i in range(len(string)):
            if string[i]=="H" and string[i+1] =="H" and toggle!=1:
                position_list.append(i)
                toggle=1
            if string [i] =="H" and string[i+1] !="H" and toggle !=0:
                toggle=0
                position_list.append(i)
       # print position_list //list of TMS locations
        runHMMTOP.cutTMS(self,record,position_list,value)
        position_list[:]=[]
    
    def cutTMS(self,record,position_list,value):
        pointer=0
        counter=1
        for i in range((len(position_list)-1)/int(value),len(position_list),(len(position_list)-1)/int(value)+1):
            if counter < int(value) :
                split_position=((position_list[i]+position_list[i+1])/2)
                print ">"+str(record.name)+str(pointer), "-", str(split_position)
                print record.seq[pointer:split_position]
                pointer=split_position+1
                counter=counter+1
            if counter == int(value):
                print ">"+str(record.name)+str(pointer),"-",str(len(record.seq))
                print record.seq[pointer:]
                counter=counter+1
                print "\n\n"
sS=submitSequence()
sS.main()
        
        
        